package com.hanbang.taitaigou.pay.wxpay;

import android.text.TextUtils;
import android.widget.Toast;

import com.hanbang.taitaigou.ui.activity.base.BaseActivity;
import com.hanbang.taitaigou.utils.http.HttpCallBack;
import com.hanbang.taitaigou.utils.http.HttpRequestParams;
import com.hanbang.taitaigou.utils.http.HttpRequestParamsWX;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2016/2/20.
 */
public class WxPay {
    private BaseActivity activity = null;
    public static String appId = "wxb00d8784793422e5";
    private String SJHAO = "1346732101";
    private OnFinshCallback onFinshCallback = null;

    public WxPay(BaseActivity activity, OnFinshCallback onFinshCallback) {
        this.activity = activity;
        this.onFinshCallback = onFinshCallback;
    }

    public interface OnFinshCallback {
        void onFinsh(boolean isSuccess);
    }

    /**
     * 开始支付
     *
     * @param id:商品id
     * @param subject : 商品名称
     * @param body    : 商品详情
     * @param subject : 商品价格 元为单位
     * @param subject : 商品订单号   应该是调用服务器  调用接口 让服务器返回订单号
     * @param extData : 回调的标示
     */
    public void wxPay(int id, String subject, String body, double price, String tradeNo, final String extData) {


        HttpRequestParams params = new HttpRequestParams();
        params.addBodyParameter("action", "GetZfbFinshCansMing");
        params.addBodyParameter("payment", String.valueOf(2));
        params.addBodyParameter("out_trade_no", tradeNo);
        params.addBodyParameter("body", subject);
        params.addBodyParameter("total_fee", String.valueOf((int) (price * 100)));
        params.addBodyParameter("detail", body);
        params.addBodyParameter("id ", String.valueOf(id));
        params.addBodyParameter("attach", "   ");
        activity.httpManager.post(params, new HttpCallBack<String>(activity, "订单生成中") {
            @Override
            public void onSuccess(String responseInfo) {
                super.onSuccess(responseInfo);

                try {
                    JSONObject json = new JSONObject(responseInfo);
                    String prepay_id = json.getString("prepay_id");
                    String sign = json.getString("sign");
                    String nonce_str = json.getString("nonce_str");
                    String timestamp = json.getString("timestamp");

                    if (!TextUtils.isEmpty(prepay_id) && !TextUtils.isEmpty(sign) && !TextUtils.isEmpty(nonce_str) && !TextUtils.isEmpty(timestamp)) {
                        //成功
                        pay(prepay_id, sign, nonce_str, timestamp, extData);
                    } else {
                        //失败
                        if (onFinshCallback != null) {
                            onFinshCallback.onFinsh(false);
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    //失败
                    if (onFinshCallback != null) {
                        onFinshCallback.onFinsh(false);
                    }
                }

            }
        });

    }


    private void pay(String prepay_id, String sign, String nonceStr, String timeStamp, String extData) {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(activity, null);
        msgApi.registerApp(appId);
        //String url = "http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=android";
        PayReq req = new PayReq();
        req.appId = appId;
        req.partnerId = SJHAO;
        req.prepayId = prepay_id;
        req.nonceStr = nonceStr;
        req.timeStamp = timeStamp;
        req.packageValue = "Sign=WXPay";
        req.sign = sign;
        req.extData = extData; // optional
        Toast.makeText(activity, "正常调起支付", Toast.LENGTH_SHORT).show();

        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
        if (req.checkArgs()) {
            msgApi.sendReq(req);
        } else {
            if (onFinshCallback != null) {
                onFinshCallback.onFinsh(false);
            }
        }

    }

    /**
     * 获取订单微信预支付的信息
     */
    public void orderPayByApp(String orderNo,final String extData){
        HttpRequestParamsWX httpRequestParamsWX = new HttpRequestParamsWX("OrderPayByApp");
        httpRequestParamsWX.addBodyParameter("orderNo",orderNo);
        activity.httpManager.post(httpRequestParamsWX, new HttpCallBack<String>(activity,null) {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);

                    String appID = jsonObject.getString("appid");
                    String shh = jsonObject.getString("partnerid");
                    String pk = jsonObject.getString("package");

                    String prepay_id = jsonObject.getString("prepayid");
                    String sign = jsonObject.getString("sign");
                    String nonce_str = jsonObject.getString("noncestr");
                    String timestamp = jsonObject.getString("timestamp");

                    if(!TextUtils.isEmpty(prepay_id)&& !TextUtils.isEmpty(sign)&&!TextUtils.isEmpty(nonce_str)&&!TextUtils.isEmpty(timestamp)){
                        //成功
//                        pay(appID,shh,pk,prepay_id,sign,nonce_str,timestamp,extData );
                        pay(prepay_id,sign,nonce_str,timestamp,extData);

                    }else{
                        //失败
                        if(onFinshCallback != null){
                            onFinshCallback.onFinsh(false);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    //失败
                    if (onFinshCallback != null) {
                        onFinshCallback.onFinsh(false);
                    }
                }
            }
        });
    }
}
